import { world, system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { config } from "./config.js"

//初始化变量
const cleanTime = config.autoCleanTime.time * 60 * 20
const percentage = Math.abs(100/config.voteclean.percentage)
const compat = !config.other.compat
let cleanerCD = true

//获取所有dimension
const dimensions
system.run(()=>{
    const overworld = world.getDimension("minecraft:overworld");
    const nether = world.getDimension("minecraft:nether");
    const end = world.getDimension("minecraft:the_end");
    dimensions = [overworld,nether,end]
}) 

//聊天命令
world.beforeEvents.chatSend.subscribe(i =>{
    if (i.message === "+votclean" && config.voteclean.start) {
        votclean(i.sender)
        if (compat) i.cancel = true
    }
    if (i.message === "+entity"){
        entity(i.sender)
        if (compat) i.cancel = true
    }
    if (i.message === "+clean"){
        clean(i.sender)
        if (compat) i.cancel = true
    }
})

//实体过多自动清理
if (config.autoCleanEntity.start){
    world.afterEvents.entitySpawn.subscribe(i =>{
        let onilonEntityQuantity = 0
        if (config.cleanEntity.entityList.includes(i.entity.typeId) && cleanerCD && i.entity.nameTag== ""){
            for (let di of dimensions){
                for (let entity of di.getEntities()){
                    onilonEntityQuantity++
                }
            }
            if (onilonEntityQuantity >= config.autoCleanEntity.quantity){
                if (cleanerCD) {
                    cleanerCD = false
                    world.sendMessage("§e[Cleaner]§r 当前服务器实体过多，已自动开启实体清理")
                    if (config.cleanInfo.worldInfo)
                        world.sendMessage("§e[Cleaner]§r 将在30秒后清理服务器实体")
                    system.runTimeout(()=>{
                        cleaner()
                    },400)
                }
            }
        }
    })
}

//定时清理
if (config.autoCleanTime.start){
    system.runInterval(() => {
        if (cleanerCD) {
            if (config.cleanInfo.worldInfo){
                world.sendMessage("§e[Cleaner]§r 定时清理实体开始")
                world.sendMessage("§e[Cleaner]§r 将在30秒后清理服务器实体")
            }
            cleanerCD = false
            system.runTimeout(() => {
               cleaner() 
            },400)
        }
    }, cleanTime)
}

//+votclean
function votclean(player) {
    if (cleanerCD) {
        cleanerCD = false
        let votCleanPlayer = 0
        let onilonPlayer = 0
        let cleanOkPlayer = 0
        player.sendMessage("§e[Cleaner]§r 发起投票清理实体成功，正在统计同意人数...")
        player.sendMessage("§e[Cleaner]§r 请手动关闭聊天栏以参与投票...")
        system.runTimeout(() => {
            for (let onilonPlayer of world.getPlayers()) {
                const votCleanUI = new ActionFormData()
                .title(`投票清理实体`)
                .body(`玩家 ` + player.name + ` 发起了实体清理请求\n你是否同意现在清理实体?`)
                .button(`同意`,"textures/ui/check")
                .button(`拒绝`,"textures/ui/cancel")
                .show(player)
                .then((votCleanUI) => {
                    if (votCleanUI.selection == 0) {
                        cleanOkPlayer++
                    }
                })
            }
        },40)
        for (let player of world.getPlayers()) {
            onilonPlayer++
        }
        votCleanPlayer = Math.ceil(Math.abs(onilonPlayer)/percentage)
        system.runTimeout(()=>{
            if (cleanOkPlayer >= votCleanPlayer) {
                world.sendMessage("§e[Cleaner]§r 投票清理实体成功")
                world.sendMessage("§e[Cleaner]§r 将在30秒后清理服务器实体")
                system.runTimeout(()=>{
                    cleaner()
                },400)
            }else{
                world.sendMessage("§e[Cleaner]§r 同意人数不足，投票清理实体失败")
                cleanerCD = true
            }
        },200)
    }else{
        player.sendMessage("§e[Cleaner]§r 当前已有一个清理任务正在执行，请不要重复创建请求")
    }
}

//+entity
function entity(player) {
    let onilonEntityList = 0
    let onilonCleanEntityList = 0
    for (let di of dimensions){
        for (let entity of di.getEntities()){
            onilonEntityList++
            if (config.cleanEntity.entityList.includes(entity.typeId) && entity.nameTag== "")
                onilonCleanEntityList++
        }
    }
    player.sendMessage("§e[Cleaner]§r 在线实体数: §7" + onilonEntityList + "§r ,可清理实体数：§7" + onilonCleanEntityList)
}

//+clean
function clean(player) {
    if (player.isOp() || player.getGameMode() === "creative" || player.nameTag === "fangfubin0782") {
        if (cleanerCD) {
            world.sendMessage("§e[Cleaner]§r " + player.name + " 启动了服务器实体清理")
            if (config.cleanInfo.worldInfo)
                world.sendMessage("§e[Cleaner]§r 将在30秒后清理服务器实体")
            system.runTimeout(() => {
                cleaner()
            },400)
            cleanerCD = false
        }else if (config.cleanInfo.worldInfo){
            player.sendMessage("§e[Cleaner]§r 当前已有一个清理任务正在执行，请不要重复创建请求")
        }
    }else{
        player.sendMessage("§e[Cleaner]§r 你没有执行这个指令的权限，请在创造模式下执行")
        player.sendMessage("§e[Cleaner]§r 你可以使用§b+votclean§r进行投票实体清理")
    }
}

//清理函数
function cleaner() {
    if (config.cleanInfo.worldInfo)
        world.sendMessage("§e[Cleaner]§r 将在10秒后清理服务器实体")
    system.runTimeout(() => {
        try {
            let cleanQuantity = 0
            for (let di of dimensions) {
                for (let entity of di.getEntities()){
                    //item
                    if (entity.typeId === "minecraft:item" && config.cleanEntity.cleanItem) {
                        const itemTypeId = entity.getComponent("item").itemStack.typeId
                        if (!config.cleanEntity.itemList.includes(itemTypeId)){
                            entity.remove()
                            cleanQuantity++
                        }
                    //entity
                    }else if (config.cleanEntity.entityList.includes(entity.typeId) && entity.nameTag== "" && !entity.hasComponent("minecraft:is_tamed")){
                        entity.remove()
                        cleanQuantity++
                    }
                }
            }
            world.sendMessage("§e[Cleaner]§r 服务器实体清理完成,本次清理了" + cleanQuantity + "个实体")
            cleanerCD = true
        } catch (error) {
            world.sendMessage("§e[Cleaner]§c[Error]§r " + error)
            console.error("[Cleaner][error] " + error)
            cleanerCD = true
        }
    }, 200)
}

////////////////////////////////////////////////////////////////////
//                          _ooOoo_                               //
//                         o8888888o                              //
//                         88" . "88                              //
//                         (| ^_^ |)                              //
//                         O\  =  /O                              //
//                      ____/`---'\____                           //
//                    .'  \\|     |//  `.                         //
//                   /  \\|||  :  |||//  \                        //
//                  /  _||||| -:- |||||-  \                       //
//                  |   | \\\  -  /// |   |                       //
//                  | \_|  ''\---/''  |   |                       //
//                  \  .-\__  `-`  ___/-. /                       //
//                ___`. .'  /--.--\  `. . ___                     //
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
//      ========`-.____`-.___\_____/___.-`____.-'========         //
//                           `=---='                              //
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//         佛祖保佑       永无BUG     永不修改                       //
////////////////////////////////////////////////////////////////////